#include <stdio.h>
#include <stdlib.h>
#include "coro.h"
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

char *global_dir;
char *global_name;
coro_t *greper;
coro_t *fs_walker;
extern void fs_walk();

void usage()
{
    puts("grep -r string dir");
}

void grep()
{
    while(1) {
        char *item = (char *) coro_resume(fs_walker);
        if (item == NULL)
            break;
        //puts(item);
        FILE *file = fopen(item, "r");
        char line[256];
        while (fgets(line, sizeof(line), file)) {
            if (strstr(line, global_name))
                printf("%s: %s\n", item, line);
        }
        fclose(file);
    }
    exit(0);
}

int main(int argc, char *argv[])
{
    if (argc != 4|| strcmp(argv[1], "-r") != 0) {
        usage();
        return 0;
    }
    global_dir = argv[3];
    global_name = argv[2];
    puts("begin\n");	 
    greper = coro_new(grep);
    fs_walker = coro_new(fs_walk);
    coro_boot(greper);
    coro_delete(greper);
    coro_delete(fs_walker);

    return 0;
}
